package com.buss.FrontController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.dao.ICommonDao;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.extend.datasource.DataSourceContextHolder;
import org.jeecgframework.core.extend.datasource.DataSourceType;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.EncryptUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.system.service.MutiLangServiceI;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.buss.user.entity.BnsUsersInfoEntity;
import com.buss.user.service.BnsUsersInfoServiceI;

/**
 * 注册控制层
 * 
 * @author hlg
 * @date 2016-08-04
 */
@Scope("prototype")
@Controller
@RequestMapping("/registerController")
public class RegisterController extends BaseController {
	private Logger log = Logger.getLogger(RegisterController.class);
	private SystemService systemService;
	private String message = null;
	public ICommonDao commonDao = null;

	@Autowired
	private MutiLangServiceI mutiLangService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private BnsUsersInfoServiceI bnsUsersInfoServiceI;

	@Autowired
	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}


	/**
	 * 注册页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goReg")
	public String goReg() {
		return "front/register"; 
	}
	
	/**
	 * 检查页面 验证密码
	 * @param user
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "register")
	@ResponseBody
	public AjaxJson register(BnsUsersInfoEntity user, HttpServletRequest req) {
		HttpSession session = ContextHolderUtils.getSession();
		DataSourceContextHolder.setDataSourceType(DataSourceType.dataSource_jeecg);
		AjaxJson j = new AjaxJson();

		String userName = req.getParameter("username");
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		password = EncryptUtil.encrypt(password, "MD5"); // 密码 MD5加密
		String qrPassWord = req.getParameter("qrPassWord");
		qrPassWord = EncryptUtil.encrypt(qrPassWord, "MD5"); // 密码 MD5加密
		String qq = req.getParameter("qq");
		String phone = req.getParameter("phone");
		String authCode = req.getParameter("authCode"); // 短信验证码
		String randCodeImageStr = req.getParameter("randCodeImageStr"); // 网页验证码

		if (req.getParameter("langCode") != null) {
			req.getSession().setAttribute("lang", req.getParameter("langCode"));
		}
		
		if (StringUtils.isEmpty(userName)) {
			j.setMsg("用户名不能为空!");
			j.setSuccess(false);
			return j;
		}

		if (StringUtils.isEmpty(email)) {
			j.setMsg("邮箱不能为空!");
			j.setSuccess(false);
			return j;
		}

		if (!password.equals(qrPassWord)) {
			j.setMsg("2次输入的密码不一样");
			j.setSuccess(false);
			return j;
		}

		if (StringUtils.isEmpty(phone)) {
			j.setMsg("电话不能为空!");
			j.setSuccess(false);
			return j;
		}
		
		if (StringUtils.isEmpty(randCodeImageStr)) {
			j.setMsg(mutiLangService.getLang("common.enter.verifycode"));
			j.setSuccess(false);
			return j;
		}else if (!randCodeImageStr.equalsIgnoreCase(String.valueOf(session.getAttribute("randCode")))) {
			// todo "randCode"和验证码servlet中该变量一样，通过统一的系统常量配置比较好，暂时不知道系统常量放在什么地方合适
			j.setMsg(mutiLangService.getLang("common.verifycode.error"));
			j.setSuccess(false);
			return j;
		}
		
		// 判断 phone 唯一性 只能有一个电话当账号
		BnsUsersInfoEntity bnsUsersInfoEntity = bnsUsersInfoServiceI.findSingleResult(phone);
		if (!StringUtil.isNotEmpty(bnsUsersInfoEntity)) { // 判断当前用户的电话不存在
			saveUser(phone, userName, qq, email, password);
			j.setMsg("注册成功");
			j.setSuccess(true);
			return j;
		} else {
			j.setMsg("当前电话已经存在!");
			j.setSuccess(false);
			return j;
		}

	}
	
	/**
	 * 保存用戶
	 * @param phone
	 * @param userName
	 * @param qq
	 * @param email
	 * @param password
	 */
	public void saveUser(String phone, String userName, String qq, String email, String password) {
		BnsUsersInfoEntity bnsUsersInfoEntity = new BnsUsersInfoEntity();
		String sql = "select max(user_id) from bns_users_info";
		List userList =commonService.findListbySql(sql);
		if(userList.get(0) != null){
			int v = (Integer) userList.get(0);
			bnsUsersInfoEntity.setUserId(v+1); // 
		}else{
			bnsUsersInfoEntity.setUserId(10000);
		}
		bnsUsersInfoEntity.setUserName(userName);
		bnsUsersInfoEntity.setMobile(phone);
		bnsUsersInfoEntity.setQq(qq);
		bnsUsersInfoEntity.setEmail(email);
		Date time = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String regTime = formatter.format(time);
		bnsUsersInfoEntity.setRegTime(regTime);
		String regIp = oConvertUtils.getIp(); // IP
		bnsUsersInfoEntity.setRegIp(regIp);
		bnsUsersInfoEntity.setPassWord(password);
		bnsUsersInfoEntity.setGender("0");//性别默认为 0-男性
		bnsUsersInfoServiceI.save(bnsUsersInfoEntity);
		
		bnsUsersInfoServiceI.userSetInit(bnsUsersInfoEntity.getUserId()); //初始化用户设置
		bnsUsersInfoServiceI.userDynamicInit(bnsUsersInfoEntity.getUserId()); //初始化动态设置 
	}
	
	
	
	@RequestMapping(params = "registerSucceed")
	public ModelAndView registerSucceed(HttpServletRequest request){
		return new ModelAndView("redirect:/indexController.do?index"); //登录成功重定向 到会员中心
	}


}